import { defineStore } from "pinia";
// 导入用户接口和方法
import { reqLogin, reqLogout } from "@/api/login";
// 仓库重置
import { resetStores } from "@/utils/resetStores";
// 用户数据获取
const useUserStore = defineStore("User", {
  state: () => {
    return {
      // 初始化从本地获取token(避免重复登录)
      token: localStorage.getItem("VUE3-TOKEN"),
      name: localStorage.getItem("VUE3-NAME"),
      id:localStorage.getItem("VUE3-USERID"),
      roleId:localStorage.getItem("VUE3-ROLEID"),
    };
  },
  // 异步请求
  actions: {
    /** 登录 */
    async userLogin(form: any) {
      const result = await reqLogin(form);
      const { code, message, token, name,id,role_id } = result.data;
      // 请求成功 200
      if (result.status === 200 && code === 200) {
        this.token = token;
        this.name = name;
        this.id=id;
        this.roleId=role_id;
        localStorage.setItem("VUE3-TOKEN", token);
        localStorage.setItem("VUE3-NAME", name);
        localStorage.setItem("VUE3-USERID", id);
        localStorage.setItem("VUE3-ROLEID", role_id);
        return message;
      } else {
        //请求失败返回报错结果
        return Promise.reject(new Error(message));
      }
    },
    /** 登出 */
    async userLogout() {
      const result = await reqLogout();
      const { code, message } = result.data;
      // 请求成功 200
      if (result.status === 200 && code === 200) {
        // 清除仓库和本地数据
        resetStores()
        return message;
      } else {
        //请求失败返回报错结果
        return Promise.reject(new Error(message));
      }
    },
    /** 移除本地存储 */
    removeUser() {
      this.token = "";
      this.name = "";
      localStorage.removeItem("VUE3-TOKEN");
      localStorage.removeItem("VUE3-NAME");
    },
  },
  getters: {},
});
export default useUserStore;
